package com.sz.mes.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.iam.entity.IamUser;
import com.diboot.iam.mapper.IamUserMapper;
import com.diboot.iam.util.IamSecurityUtils;
import com.sz.mes.entity.warehouse.LatticeGoods;
import com.sz.mes.mapper.OutboundMapper;
import com.sz.mes.mapper.warehouse.LatticeGoodsMapper;
import com.sz.mes.vo.ShelfIdAndGoodQuantityVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.diboot.core.vo.*;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.sz.mes.entity.Outbound;
import com.sz.mes.dto.OutboundDTO;
import com.sz.mes.vo.OutboundListVO;
import com.sz.mes.vo.OutboundDetailVO;
import com.sz.mes.service.OutboundService;
import com.sz.mes.controller.BaseCustomCrudRestController;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Valid;
import java.util.List;

/**
 * 出库 相关Controller
 *
 * @author hem
 * @version 1.0
 * @date 2023-05-25
 * Copyright © szhs
 */
@RestController
@RequestMapping("/outbound")
@BindPermission(name = "出库")
@Slf4j
public class OutboundController extends BaseCustomCrudRestController<Outbound> {

    @Autowired
    private OutboundService outboundService;

    @Autowired
    private IamUserMapper iamUserMapper;

    @Autowired
    private LatticeGoodsMapper latticeGoodsMapper;

    /**
     * 查询ViewObject的分页数据
     * <p>
     * url请求参数示例: /list?field=abc&pageIndex=1&orderBy=abc:DESC
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    // @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/list")
    public JsonResult getViewObjectListMapping(OutboundDTO queryDto, Pagination pagination) throws Exception {
        QueryWrapper<Outbound> outboundQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(queryDto.getOutboundNum())) {
            outboundQueryWrapper.like("outbound_num", queryDto.getOutboundNum());
        } else if (!StringUtils.isEmpty(queryDto.getTaskNum())) {
            outboundQueryWrapper.like("task_num", queryDto.getTaskNum());
        } else {
            return super.getViewObjectList(queryDto, pagination, OutboundListVO.class);
        }
        return super.getEntityListWithPaging(outboundQueryWrapper, pagination);
    }

    /**
     * 根据备料id查询备料详情
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/getDetail")
    public JsonResult getDetail(@Param("id") Long id) throws Exception {
        return outboundService.getDetail(id);
    }

    /**
     * 根据备料id查询出库详情
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/getOutboundDetail")
    public JsonResult getOutboundDetail(@Param("id") Long id) throws Exception {
        return outboundService.getOutboundDetail(id);
    }

    /**
     * 创建资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/")
    public JsonResult createEntityMapping(@Valid @RequestBody OutboundDTO entity) throws Exception {
        List<ShelfIdAndGoodQuantityVO> outFromLatticeList = entity.getOutFromLatticeList();
        QueryWrapper<LatticeGoods> latticeGoodsQueryWrapper = new QueryWrapper<>();
//        latticeGoodsQueryWrapper.eq("goods_code", entity.getGoodsCode());
        if (entity.getOutboundType().equals("SCCK")) {
            for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : outFromLatticeList) {
                List<String> shelfList = shelfIdAndGoodQuantityVO.getShelfName();
                String shelfName = shelfList.get(0);
                String goodsCode = shelfIdAndGoodQuantityVO.getGoodsCode();
                latticeGoodsQueryWrapper.eq("goods_code", goodsCode);
//                latticeGoodsQueryWrapper.eq("warehouse_lattice_id", shelfIdAndGoodQuantityVO.getLatticeId());
                latticeGoodsQueryWrapper.eq("lable", shelfName);
                List<LatticeGoods> latticeGoodsList = latticeGoodsMapper.selectList(latticeGoodsQueryWrapper);
//                if (latticeGoodsList.size() <= 0) {
//                    return JsonResult.FAIL_OPERATION("创建失败,请检查出库信息是否与入库一致," + "请检查" + shelfName + "信息");
//                }
            }
        } else if (entity.getOutboundType().equals("FSCCK")) {
            // latticeGoodsQueryWrapper.eq("",);
            for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : outFromLatticeList) {
                List<String> shelfList = shelfIdAndGoodQuantityVO.getShelfName();
                String shelfName = shelfList.get(0);
                String goodsCode = shelfIdAndGoodQuantityVO.getGoodsCode();
                latticeGoodsQueryWrapper.eq("goods_code", goodsCode);
//                latticeGoodsQueryWrapper.eq("warehouse_lattice_id", shelfIdAndGoodQuantityVO.getLatticeId());
                latticeGoodsQueryWrapper.eq("lable", shelfName);
                List<LatticeGoods> latticeGoodsList = latticeGoodsMapper.selectList(latticeGoodsQueryWrapper);
//                if (latticeGoodsList.size() <= 0) {
//                    return JsonResult.FAIL_OPERATION("创建失败,请检查出库信息是否与入库一致," + "请检查" + shelfName + "信息");
//                }
            }
        } else if (entity.getOutboundType().equals("ZSCK")) {
            for (ShelfIdAndGoodQuantityVO shelfIdAndGoodQuantityVO : outFromLatticeList) {
                List<String> shelfList = shelfIdAndGoodQuantityVO.getShelfName();
                String shelfName = shelfList.get(0);
                Long goodsId = shelfIdAndGoodQuantityVO.getGoodsId();
                latticeGoodsQueryWrapper.eq("goods_id", goodsId);
                latticeGoodsQueryWrapper.eq("warehouse_lattice_id", shelfIdAndGoodQuantityVO.getLatticeId());
                latticeGoodsQueryWrapper.eq("lable", shelfName);
                LatticeGoods latticeGoods = latticeGoodsMapper.selectOne(latticeGoodsQueryWrapper);
//                if (latticeGoods == null) {
//                    return JsonResult.FAIL_OPERATION("创建失败,请检查出库信息是否与入库一致," + "请检查" + shelfName + "信息");
//                }
            }
        }
        super.createEntity(entity);
        Long currentUserId = IamSecurityUtils.getCurrentUserId();
        IamUser iamUser = iamUserMapper.selectById(currentUserId);
        entity.setCreateBy(iamUser.getRealname());
        entity.setUpdateBy(iamUser.getRealname());
        super.updateEntity(entity.getId(), entity);
        JsonResult jsonResult = outboundService.otherOperation(entity);
        System.out.println(jsonResult.getMsg() + "          ");
        if (!jsonResult.getMsg().equals("操作成功")) {
            outboundService.deleteEntity(entity.getId());
            return JsonResult.FAIL_OPERATION("创建失败");
        } else {
            return jsonResult;
        }
    }

    /**
     * 销售出库、杂收出库
     *
     * @param outboundList
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/outbound")
    public JsonResult outbound(@RequestBody List<Outbound> outboundList) throws Exception {
        return outboundService.outbound(outboundList);
    }


    /**
     * 根据ID更新资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    // @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult updateEntityMapping(@PathVariable("id") Long id, @Valid @RequestBody Outbound entity) throws Exception {
        return super.updateEntity(id, entity);
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    // @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
        return super.deleteEntity(id);
    }

    /**
     * 撤销出库
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/unOutbound")
    public JsonResult unOutbound(@RequestBody Outbound entity) throws Exception {
        return outboundService.unOutbound(entity);
    }

    /**
     * 签收
     *
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/receive")
    public JsonResult receive(@Param("outboundId") Long outboundId) throws Exception {
        return outboundService.receive(outboundId);
    }

    /**
     * 获取出库单号
     *
     * @return
     */
    @GetMapping("/getNumber")
    public JsonResult getNumber() {
        long time = System.currentTimeMillis();
        return JsonResult.OK("CK" + time);
    }

    /**
     * 查询计划备料信息
     *
     * @param taskNum
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.LABEL_DETAIL)
    @GetMapping("/getProductInfo/{taskNum}")
    public JsonResult getProductInfoByTaskNum(@PathVariable("taskNum") String taskNum) throws Exception {
        return outboundService.getProductInfoByTaskNum(taskNum);
    }

    /**
     * 根据单据编号查询计划备料信息
     *
     * @param receiptNum
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.LABEL_DETAIL)
    @GetMapping("/getProductInfoByReceiptNum/{receiptNum}")
    public JsonResult getProductInfo(@PathVariable("receiptNum") String receiptNum) throws Exception {
        return outboundService.getProductInfoByReceiptNum(receiptNum);
    }

    /**
     * 根据任务单查询料品料号信息
     *
     * @param
     * @return
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.LABEL_DETAIL)
    @GetMapping("/getProductShipInfoByOrderNum/{orderNum}")
    public JsonResult getProductShipInfo(@PathVariable("orderNum") String orderNum) {
        return outboundService.getProductShipInfoByOrderNum(orderNum);
    }

    /**
     * 根据料号查询料品信息
     *
     * @param
     * @return
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.LABEL_DETAIL)
    @GetMapping("/getMiscShipmentInfos/{goodsCode}")
    public JsonResult getMiscShipmentInfos(@PathVariable("goodsCode") String goodsCode) {
        return outboundService.getMiscShipmentInfos(goodsCode);
    }

    /**
     * 根据出库单号查询出库详情
     *
     * @param outboundNum
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{outboundNum}")
    public JsonResult detail(@PathVariable("outboundNum") String outboundNum) throws Exception {
        return outboundService.getOutboundInfo(outboundNum);
    }

    /**
     * 根据销售订单号查询出库数量之和
     *
     * @param taskNumAndGoodsCode
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/getTotalQuantityBySO/{taskNumAndGoodsCode}")
    public JsonResult getTotalQuantityBySO(@PathVariable("taskNumAndGoodsCode") String taskNumAndGoodsCode) throws Exception {
        return outboundService.getTotalQuantityBySO(taskNumAndGoodsCode);
    }

    /**
     * 根据销售订单号及行号查询该订单的所有内容
     *
     * @param orderNumAndRow
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/getSaleOrderInfo/{orderNumAndRow}")
    public JsonResult getSaleOrderInfo(@PathVariable("orderNumAndRow") String orderNumAndRow) throws Exception {
        return outboundService.getSaleOrderInfo(orderNumAndRow);
    }

    /**
     * 根据生产单据编号查询出库数量之和
     *
     * @param receiptNum
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/getTotalQuantity/{receiptNum}")
    public JsonResult getTotalQuantity(@PathVariable("receiptNum") String receiptNum) throws Exception {
        return outboundService.getTotalQuantity(receiptNum);
    }
}
